package org.kia.data.adapters;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedList;

import org.kia.data.adapters.droidfu.DroidFuRequestAdapter;
import org.kia.data.adapters.droidfu.DroidFuRequestFactory;

import android.os.Bundle;
import android.util.Log;

/**
 * @author Amir Lazarovich
 */
public class RequestFactory {

	private static final String TAG = "RequestFactory";
	
    /**
     * Creates a HttpGet request
     *
     * @param uri
     * @param params
     * @param authentication
     * @return
     */
    public static RequestAdapter createGetRequest(String uri, Bundle params) {
        uri = addPathParams(uri, params);
        DroidFuRequestAdapter adapter = DroidFuRequestFactory.createGetRequest(uri);
        return adapter;
    }

    
    public static RequestAdapter createPostRequest(String uri, Bundle params) {
        uri = addPathParams(uri, params);
        DroidFuRequestAdapter adapter = DroidFuRequestFactory.createPostRequest(uri, null);
        return adapter;
    }
    
    /**
     * Replace uri pattern path parameters with their corresponding values
     *
     * @param uri
     * @param params
     * @return
     */
    private static String addPathParams(String uri, Bundle params) {
        if (params == null) {
            return uri;
        }

        StringBuilder sb = new StringBuilder("?");
        String tmpKey;
        String value;
        LinkedList<String> keyset = null;
        // Add REST params and collect all GET params
        for (String key : params.keySet()) {
            tmpKey = "{" + key + "}";
            try {
				value = URLEncoder.encode(params.getString(key), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				Log.e(TAG, "Couldn't encode URI values", e);
				value = params.getString(key);
			}
            if (uri.contains(tmpKey)) {
                uri = uri.replace(tmpKey, value);
            } else {
            	sb.append(key);
            	sb.append("=");
            	sb.append(value);
            	sb.append("&");
            }
        }
        
        // Add GET params (if there are any)
        sb.insert(0, uri);
        
        // Remove unnecessary chars
        sb.deleteCharAt(sb.length() - 1);

        return sb.toString();
    }


}
